package com.gccloud.design.utils;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import org.codehaus.groovy.runtime.InvokerHelper;

import java.io.IOException;

/**
 * 实现功能【Groovy解析工具类】
 *
 * @author hu.hongdou
 * @date 2022/2/21 12:14
 */
public class GroovyUtil {
    public GroovyUtil() {
    }

    public static Class<?> parseClass(String groovyScript) {
        ClassLoader parent = GroovyUtil.class.getClassLoader();
        GroovyClassLoader loader = new GroovyClassLoader(parent);
        Class groovyClass = loader.parseClass(groovyScript);

        try {
            loader.close();
        } catch (IOException var5) {
            var5.printStackTrace();
        }

        return groovyClass;
    }

    public static Object executeGroovy(Class<?> groovyClass, Object param) {
        Binding binding = new Binding();
        binding.setVariable("$groovyParam", param);
        Script script = InvokerHelper.createScript(groovyClass, binding);
        Object result = script.run();
        return result;
    }
}
